package com.ruoyi.system.task;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateTimeUtils;
import com.ruoyi.common.utils.PrintUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WhOrder;
import com.ruoyi.system.domain.WhPrintLog;
import com.ruoyi.system.mapper.WhOrderMapper;
import com.ruoyi.system.mapper.WhPrintLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: 陈平安
 * @date: 2023/3/13 17:12
 * @description: 订单状态定时任务
 */
@Slf4j
@Configuration
public class OrderPrintStatusTask {

    @Resource
    private RedisCache redisCache;
    @Resource
    private WhPrintLogMapper printLogMapper;
    @Resource
    private PrintUtils printUtils;
    @Resource
    private WhOrderMapper orderMapper;

    private static final String ORDER_TASK_LOCK = "order:status:task";

    @Scheduled(cron ="0 0/1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void changeOrderStatus() {
        log.info("进来执行定时任务：{}", DateTimeUtils.formatDateTime(new Date()));
        String lock = UUID.randomUUID().toString();
        String lockValue = (String) redisCache.getAndSet(ORDER_TASK_LOCK,lock, 60 * 10);
        if (!lockValue.equals(lock)) {
            log.error("更新订单状态任务获取锁失败：", DateTimeUtils.formatDateTime(new Date()));
            return;
        }
        WhPrintLog printLog = new WhPrintLog();
        printLog.setStatus(1);
        try {
            // 查询所有队列中的订单
            List<WhPrintLog> list = printLogMapper.selectWhPrintLogList(printLog);
            if (CollectionUtil.isEmpty(list)) {
                return;
            }
            for (WhPrintLog item : list) {
                if (StringUtils.isEmpty(item.getPrintId())) {
                    continue;
                }
                // 查询打印状态
                boolean printsStatus = printUtils.getPrintsStatus(item.getPrintId());
                // 更新打印状态
                WhOrder orderInfo = new WhOrder();
                orderInfo.setId(Integer.parseInt(item.getOrderId()));
                orderInfo.setStatus(printsStatus ? 2 : 1);
                int i = orderMapper.updateWhOrder(orderInfo);
                if (i > 0 && printsStatus) {
                    item.setStatus(2);
                    printLogMapper.updateWhPrintLog(item);
                }
            }
        } catch (Exception e) {
            log.error("更新打印状态发生错误：{}", e.getMessage());
        } finally {
            redisCache.deleteObject(ORDER_TASK_LOCK);
        }
    }
}
